package com.demo.crm.model;

import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 把httpRequest请求转成这个对象
 *
 * @author tanshuai
 */
@Data
public class RequestInfo {

    /**
     * 请求路径
     */
    private String url;

    private String ip;

    public RequestInfo(String url) {
        this.url = url;
    }

    /* 以后根据项目需要，可进行字段的扩展*/
    public static RequestInfo create(HttpServletRequest request) {
        String url = StringUtils.substring(request.getServletPath(), 1);
        String pathInfo = request.getPathInfo();
        String query = request.getQueryString();

        if (pathInfo != null || query != null) {
            StringBuilder sb = new StringBuilder(url);

            if (pathInfo != null) {
                sb.append(pathInfo);
            }

            if (query != null) {
                sb.append('?').append(query);
            }
            url = sb.toString();
        }

        RequestInfo requestInfo = new RequestInfo(url);
        requestInfo.setIp(request.getRemoteAddr());
        return requestInfo;
    }
}
